import { useState, useEffect } from 'react';
import { useModel } from 'umi';
import { Table, message, Select, Button, Space, Input } from 'antd';
const { Option } = Select;
import {
  teacherService,
  experimentScoreService, experimentCourseService,
} from '@/service';
import { executeActionAfterReq } from '@/util/errorHandle';
import styles from './index.less';

function ExperimentCoursePage() {
  const { teacher } = useModel('useTeacher');
  const [ecIds, setEcIdsData] = useState([]);
  const [studentData, setStudentData] = useState([]);
  const [selectOption, setSelectOption] = useState([]);
  const [theId, setTheId] = useState('');
  const [filters, setFilters] = useState([]);
  useEffect(() => {
    getAllTeacher();
  }, [teacher]);
  useEffect(() => {
    getAllExperimentCourse();
  }, [ecIds]);

  
  const getAllTeacher = async () => {
    const res = await teacherService.getAllTeacher().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      setEcIdsData((res?.data
        ?.find((item: any) => teacher?.tId == item?.tId)
        ?.ecIds || '')
        ?.split(',')
        ?.filter((item: any) => item)
        ?.map((item: any) => Number(item))
      );
    })
  }

  const getAllExperimentCourse = async () => {
    const res = await experimentCourseService.getAllExperimentCourse().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      setSelectOption(res?.data
        .filter((item: any) => ecIds.includes(item?.ecId))
        .map((item: any) => ({
          id: item.ecId,
          title: item.ecTitle,
        })));
    });
  }

  const reqData = async (id = theId) => {
    if (!id) {
      message.error('请选择课程');
      return;
    }
    const res = await experimentScoreService.getAllExperimentScore().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      const data = res?.data
      .filter((item: any) => id == item.ecId)
      .map((item: any) => ({
        sId: item.sId,
        ecId: item.ecId,
        score: item.score,
        sName: item.Student.sName,
        tcId: item.Student.tcId,
        disabled: true,
      }));
      setStudentData(data);
      setFilters(Array
        .from(new Set(data.map((item: any) => item.tcId)))
        .map((item: any) => ({
          text: item,
          value: item,
        })));
    });
  }
  const onChange = (id: string) => {
    setTheId(id);
    reqData(id);
  }

  const columns = [
    {
      title: '学号',
      dataIndex: 'sId',
      key: 'sId',
      sorter: (a: any, b: any) => a.sId - b.sId,
      sortDirections: ['ascend'],
    },
    {
      title: '姓名',
      dataIndex: 'sName',
      key: 'sName',
      sorter: (a: any, b: any) => a.sName - b.sName,
      sortDirections: ['ascend'],
    },
    {
      title: '班级编号',
      dataIndex: 'tcId',
      key: 'tcId',
      filters,
      onFilter: (value: any, record: any) => record.tcId == value,
    },
    {
      title: '成绩',
      dataIndex: 'score',
      key: 'score',
      sorter: (a: any, b: any) => a.score - b.score,
      sortDirections: ['ascend'],
      render: (text: any, record: any) => (
        <Input key={text} placeholder={text} disabled={record.disabled} allowClear 
          onPressEnter={(e) => handleSummit(e, record)} className={styles.input} 
          onBlur={(e) => handleCancel(e, record)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (text: any, record: any) => (
        <Space size="middle">
          <Button type="link" size ="small" className={styles.link} onClick={() => handleEdit(record)}>成绩录入</Button>
        </Space>
      ),
    },
  ]

  const handleEdit = (record: any) => {
    record.disabled = false;
    setStudentData([...studentData]);
  }
  const handleCancel = (e: any, record: any) => {
    record.disabled = true;
    setStudentData([...studentData]);
  }
  const handleSummit = async (e: any, record: any) => {
    record.score = Number(e?.target?.value);
    const res = await experimentScoreService.updateExperimentScore({ ...record }).catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, async () => {
      message.info('录入成功');
      record.disabled = true;
      setStudentData([...studentData]);
    });
  }
  
  return (
    <div className={styles.student}>
      <div className={styles.course}>
        <span>任教的实验课程: </span>
        <Select
          placeholder="请选择课程"
          onChange={onChange}
          className={styles.select}
        >
          {
            selectOption.map((course: any) => <Option value={course?.id}>{`${course?.id}: ${course?.title}`}</Option>)
          }
        </Select>
        <Button type="primary" htmlType="button" className={styles.button} onClick={() => reqData()}>
          确认课程
        </Button>
      </div>
      <Table dataSource={studentData} columns={columns} style={{minHeight: "400px"}} />
    </div>
  );
}

export default ExperimentCoursePage;
